﻿/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://git.oschina.net/cblock/embedme
 * Copyright 2014~2017 @ ShenZhen ,China
*******************************************************************************/
#ifndef __EVENT_H__
#define __EVENT_H__

#include "BaseType.h"
#include "Thread.h"
#include "Mutex.h"

#include<list>

#define EVENT_PARAM_MAXLEN      128      /**< 定义事件传递的参数最大长度 */

/* 事件ID:高16位为事件类型,低16位为该类型事件的事件源ID */
typedef enum{
    EVENT_TYPE_TIMER = 0x0000,
    EVENT_TYPE_HSKEY,
    EVENT_TYPE_MODEM,
}EVENT_TYPE_E;

#define EVENT_ID(evttype,srcid)    (((evttype)<<16)+srcid)    /* 事件ID */

/**
 *  \file   Event.h   
 *  \class  Event
 *  \brief  事件类.
 */

class Event{
public:
    Event(int eventID, void* param=NULL, int len=0);
    Event(const Event&);
    ~Event();
    int getEventId();
    int getParam(void* buf,int len);  /* 获取事件携带的数据 */
private:
    int  m_eventID;
    char    m_eventParam[EVENT_PARAM_MAXLEN];
    int  m_eventParamLen;
};


/**
 *  \file   Event.h   
 *  \class  EventListner
 *  \brief  事件处理者抽象类.
 */
class EventListner{
public:
    EventListner(){};
    virtual ~EventListner(){};
    virtual void handleEvent(Event& evt)=0;
};

class EventCenter;
/**
 *  \file   Event.h   
 *  \class  EventDispatcher
 *  \brief  Observer模式实现的事件管理器,不对外开放接口.
 */
class EventDispatcher:public Runnable{
public:
    virtual ~EventDispatcher();
    void registerListener(EventListner* pEvtHandler);
    void unregisterListener(EventListner* pEvtHandler);
    void postEvent(Event& evt);
private:
    EventDispatcher();
    void run();
private:
    friend class EventCenter;
    Thread m_ecThread;
    std::list<EventListner*> m_evtListenerList;
    std::list<Event> m_eventList;
    MutexLock m_eventLock;
    MutexLock m_listenerLock;
};


/**
 *  \file   Event.h   
 *  \class  EventCenter
 *  \brief  事件中心类,EventDispatcher的适配器,便于继承.
 */
class EventCenter{
public:
    EventCenter();
    virtual ~EventCenter();
    void addEventListener(EventListner* listener);
    void delEventListener(EventListner* listener);
    void postEvent(Event& evt);
private:
    EventDispatcher* m_eventDispatcher;
};


#endif
